import { http } from '@/utils/http'
import { useMemberStore } from '@/stores/modules/member'
const memberStore = useMemberStore()
const baseURL = import.meta.env.DEV ? '/h5image' : 'https://image.queqiao77.top'

const uploadImage = (data: any) => {
  return http<{ fileID: string }>({
    method: 'POST',
    url: `${baseURL}/upload`,
    data,
  })
}

export function ImgUpload(url?: string) {
  // #ifdef H5
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      let image = (res.tempFiles as any[])[0]
      // 如果图片大于1M，进行压缩
      if (image.size > 1024 * 1024) {
        image = await compressImage(image)
      }
      const base = await getBase64(image)
      const imageFile = await uploadImage(base)
      // 根据是否传入url决定替换还是追加图片
      if (url) {
        // 如果传入了url，替换对应位置的图片
        const imgArray = memberStore.profile!.imgList ? memberStore.profile!.imgList.split(',') : []
        const index = imgArray.indexOf(url)
        if (index !== -1) {
          imgArray[index] = imageFile.data.fileID
          memberStore.profile!.imgList = imgArray.join(',')
        }
      } else {
        // 如果没有传入url，追加新图片
        const currentImgList = memberStore.profile!.imgList || ''
        memberStore.profile!.imgList = currentImgList
          ? `${currentImgList},${imageFile.data.fileID}`
          : imageFile.data.fileID
      }
      memberStore.updateProfile(memberStore.profile!)
    },
  })
  // #endif

  // #ifdef MP-WEIXIN
  // uni.chooseMedia({
  //   count: 1,
  //   mediaType: ['image'],
  //   success: (res) => {
  //     const tempFiles = res.tempFiles[0]
  //     // 小程序端使用uni.compressImage进行压缩
  //     if (tempFiles.size > 1024 * 1024) {
  //       uni.compressImage({
  //         src: tempFiles.tempFilePath,
  //         quality: 80,
  //         success: (res) => {
  //           handleWeixinImage(res.tempFilePath)
  //         },
  //         fail: () => {
  //           handleWeixinImage(tempFiles.tempFilePath)
  //         },
  //       })
  //     } else {
  //       handleWeixinImage(tempFiles.tempFilePath)
  //     }
  //   },
  // })
  // #endif
}

export function fileUpload() {
  // #ifdef H5
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      let image = (res.tempFiles as any[])[0]
      // 如果图片大于1M，进行压缩
      if (image.size > 1024 * 1024) {
        image = await compressImage(image)
      }
      const base = await getBase64(image)
      const imageFile = await uploadImage(base)
      memberStore.profile!.headPortrait = imageFile.data.fileID
      memberStore.updateProfile(memberStore.profile!)
    },
  })
  // #endif

  // #ifdef MP-WEIXIN
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    success: (res) => {
      const tempFiles = res.tempFiles[0]
      // 小程序端使用uni.compressImage进行压缩
      if (tempFiles.size > 1024 * 1024) {
        uni.compressImage({
          src: tempFiles.tempFilePath,
          quality: 80,
          success: (res) => {
            handleWeixinImage(res.tempFilePath)
          },
          fail: () => {
            handleWeixinImage(tempFiles.tempFilePath)
          },
        })
      } else {
        handleWeixinImage(tempFiles.tempFilePath)
      }
    },
  })
  // #endif
}

// 处理微信小程序图片的函数
function handleWeixinImage(filePath: string) {
  uni.getImageInfo({
    src: filePath,
    success: (image) => {
      if (image.type == 'png' || image.type == 'jpeg') {
        uni.getFileSystemManager().readFile({
          filePath: image.path,
          encoding: 'base64',
          success: (res) => {
            const imageBase64 = 'data:image/' + image.type + ';base64,' + res.data
            uni.request({
              url: 'https://tea.qingnian8.com/filedemo',
              data: imageBase64,
              method: 'POST',
              success: (res) => {
                memberStore.profile!.headPortrait = (res.data as any).fileID
                memberStore.updateProfile(memberStore.profile!)
              },
            })
          },
        })
      } else {
        uni.showToast({
          title: '当前只支持png/jpeg格式',
          duration: 2500,
          icon: 'none',
        })
      }
    },
  })
}

//上传图片核心函数，将图片转base64，小程序和H5的方式不同，下面有条件编译
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    ///FileReader类就是专门用来读文件的
    const reader = new FileReader()
    //开始读文件
    //readAsDataURL: dataurl它的本质就是图片的二进制数据， 进行base64加密后形成的一个字符串，
    reader.readAsDataURL(file)
    // 成功和失败返回对应的信息，reader.result一个base64，可以直接使用
    reader.onload = () => resolve(reader.result)
    // 失败返回失败的信息
    reader.onerror = (error) => reject(error)
  })
}

// 压缩图片函数
function compressImage(file: File): Promise<File> {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      const img = new Image()
      img.src = e.target?.result as string
      img.onload = () => {
        const canvas = document.createElement('canvas')
        let width = img.width
        let height = img.height

        // 计算压缩比例
        const maxSize = 1024 * 1024 // 1MB
        let ratio = 1
        if (file.size > maxSize) {
          ratio = Math.sqrt(maxSize / file.size)
          width *= ratio
          height *= ratio
        }

        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d')
        ctx?.drawImage(img, 0, 0, width, height)

        // 转换为blob
        canvas.toBlob(
          (blob) => {
            if (blob) {
              const newFile = new File([blob], file.name, {
                type: file.type,
                lastModified: Date.now(),
              })
              resolve(newFile)
            } else {
              resolve(file)
            }
          },
          file.type,
          0.8,
        )
      }
    }
  })
}
